//
//  LXJComposeWeiboController.swift
//  XJWeiBo
//
//  Created by 李旭杰 on 2017/4/5.
//  Copyright © 2017年 李旭杰. All rights reserved.
//

import UIKit
import SVProgressHUD

@available(iOS 9.0, *)
class LXJComposeWeiboController: UIViewController {
    
    // MARK: 控件的懒加载
    /// 标题
    fileprivate lazy var titleView: UILabel = {
        let label = UILabel(text: "发微博", font: 15, textColor: UIColor.black, textAlignment: .center)
        if let name = LXJOAuthViewModel.sharedOAuthViewModel.userAccount?.name {
            let message = "发微博\n" + name
            ///  获取名字的范围
            let range = (message as NSString).range(of: name)
            ///  创建富文本
            let attributedStr: NSMutableAttributedString = NSMutableAttributedString(string: message)
            ///  设置name文字的颜色和字体大小
            attributedStr.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 12), NSForegroundColorAttributeName: UIColor.orange], range: range)
            ///  需要设置富文本
            label.attributedText = attributedStr
        } else {
            ///  没有登录也就是没有名字
            label.text = "发微博"
        }
        /// 大小适配
        label.sizeToFit()
        return label
    }()
    
    /// 发送
    fileprivate lazy var sendButton: UIButton = {
        let button = UIButton()
        ///  设置文字
        button.setTitle("发送", for: .normal)
        button.setTitleColor(UIColor.white, for: .normal)
        button.setTitleColor(UIColor.darkGray, for: .disabled)
        ///  设置字体大小
        button.titleLabel?.font = UIFont.systemFont(ofSize: 13)
        ///  设置不同状态的背景图片
        button.setBackgroundImage(UIImage(named: "common_button_orange"), for: .normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), for: .highlighted)
        /// 获取图片
        var image = UIImage(named: "common_button_white_disable")
        /// 切图
        image = image?.resizableImage(withCapInsets: UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1), resizingMode: .stretch)
        /// 设置禁用图片
        button.setBackgroundImage(image, for: .disabled)
        ///  设置大小
        button.size = CGSize(width: 45, height: 30)
        ///  添加点击事件
        button.addTarget(self, action: #selector(sendAction), for: .touchUpInside)
        return button
    }()
    
    /// 文字输入框
    fileprivate lazy var  weiboContentTextView: LXJTextView = {
        let textview = LXJTextView()
        /// 设置占位文字
        textview.placeHolder = "听说我们要毕业了,真实一个恐怖的故事..."
        /// 设置代理对象
        textview.delegate = self
        /// 滚动方向
        textview.alwaysBounceVertical = true
        return textview
    }()
    
    /// 发微博的工具条
    fileprivate lazy var composeWeiboToolBar: LXJComposeWeiboToolBar = LXJComposeWeiboToolBar()
    
    /// 多图页面
    fileprivate lazy var composeWeiboPictures: LXJComposeWeiboPicturesView = {
        /// 布局对象
        let flowLayout = UICollectionViewFlowLayout()
        /// 间距
        let margin: CGFloat = 5
        flowLayout.minimumLineSpacing = margin
        flowLayout.minimumInteritemSpacing = margin
        /// 每个控件的大小
        let itemWidth = CGFloat((ScreenWidth - 20 - 10) / 3)
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        
        /// 创建多图画板
        let collectionView = LXJComposeWeiboPicturesView(frame: CGRect.zero, collectionViewLayout: flowLayout)
        
        return collectionView
    }()
    
    /// 表情键盘
    fileprivate lazy var emoticonKeyBoard: LXJEmoticonKeyBoard = {
        let keyBoard = LXJEmoticonKeyBoard()
        keyBoard.size = CGSize(width: self.weiboContentTextView.width, height: 216)
        return keyBoard
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        /// 界面搭建
        setupUI()
    }
    
    // MARK: 页面搭建
    fileprivate func setupUI() -> Void {
        /// 设置背景颜色
        view.backgroundColor = UIColor.white
        
        /// 搭建 nav 的界面
        setupNavUI()
        /// 添加子控件
        view.addSubview(weiboContentTextView)
        view.addSubview(composeWeiboToolBar)
        weiboContentTextView.addSubview(composeWeiboPictures)
        
        /// 自动布局
        weiboContentTextView.snp.makeConstraints { (make) in
            make.top.leading.equalTo(self.view).offset(homeWeiboCellmargin)
            make.trailing.equalTo(self.view).offset(-homeWeiboCellmargin)
            make.bottom.equalTo(composeWeiboToolBar.snp.top)
        }
        
        /// 多图画布的宽
        let composeWeiboPicturesWidth = ScreenWidth - 2 * CGFloat(homeWeiboCellmargin)
        
        composeWeiboPictures.snp.makeConstraints { (make) in
            make.top.equalTo(weiboContentTextView).offset(100)
            make.centerX.equalTo(weiboContentTextView)
            make.size.equalTo(CGSize(width: composeWeiboPicturesWidth, height: composeWeiboPicturesWidth))
        }
        
        composeWeiboToolBar.snp.makeConstraints { (make) in
            make.leading.bottom.trailing.equalTo(self.view)
            make.height.equalTo(35)
        }
        
        /// 监听键盘的 frame 的改变的通知
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardFrameChanged(notice:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        
        /// 在表情键盘点击删除摁扭的时候需要执行的通知
        NotificationCenter.default.addObserver(self, selector: #selector(deleteTextAction), name: NSNotification.Name("DidSelectedDeleteEmoticonNotification"), object: nil)
        /// toolbar 的摁扭点击时候的闭包回调
        composeWeiboToolBar.composeToolBarButtonClickClosure = {[weak self] (type: ComposeToolBarButtonType) -> () in
            
            switch type {
            case .picture:
                /// 弹出图片选择器
                self?.didSelectedPicture()
                
            case .mention:
                print("@")
                
            case .trend:
                print("话题")
                
            case .emoticon:
                /// 弹出表情键盘
                self?.didEmoticonKeyBoard()
                
            case .add:
                print("➕")
                
            }
        }
        
        /// 点击加号摁扭的闭包回调
        composeWeiboPictures.addPictureClosure = {
            /// 添加图片 弹出图片选择器
            self.didSelectedPicture()
        }
        
        
    }
    fileprivate func setupNavUI() -> Void {
        /// 左边的取消摁扭
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target:  self, action: #selector(cancelAction))
        /// 中间的标题视图
        navigationItem.titleView = titleView
        /// 右边的发送摁扭
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        /// 默认状态下右边的发送摁扭禁用
        navigationItem.rightBarButtonItem?.isEnabled = false
    }
    
    // MARK: navbar 摁扭的点击事件
    /// 取消摁扭
    @objc fileprivate func cancelAction() {
        /// 键盘消失
        self.view.endEditing(true)
        /// 销毁控制器
        dismiss(animated: true, completion: nil)
    }
    /// 发送摁扭
    @objc fileprivate func sendAction() {
        /// 获取令牌
        let accessToken = LXJOAuthViewModel.sharedOAuthViewModel.userAccount?.access_token!
        
        /// 获取微博内容
        let status = weiboContentTextView.text
        
        /// 弹框
        SVProgressHUD.show()

        /// 判断是否有图片
        if composeWeiboPictures.selecetedImagesArray.count == 0 {
            /// 发起网络请求
            LXJNetworkManager.sharedManager.sendWeiboMessage(access_token: accessToken!, status: status!) { (_, error) in
                /// 发送失败
                if error != nil{
                    print("微博发送失败\(error!)")
                    SVProgressHUD.showError(withStatus: "发送失败")
                } else{
                    SVProgressHUD.showSuccess(withStatus: "发送成功")
                }
            }
        } else {/// 没有图片
            /// 获取图片
            let image = composeWeiboPictures.selecetedImagesArray.first
            
            /// 发起网络请求
            LXJNetworkManager.sharedManager.sendWeiboMessage(access_token: accessToken!, status: status!, image: image!, completion: { (_, error) in
                /// 发送失败
                if error != nil{
                    print("微博发送失败\(error!)")
                    SVProgressHUD.showError(withStatus: "发送失败")
                } else{
                    SVProgressHUD.showSuccess(withStatus: "发送成功")
                }
            })
        }
        /// 销毁当前控制器
        self.dismiss(animated: true, completion: nil)
    }
    /// 点击屏幕进行销毁
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        dismiss(animated: true, completion: nil)
    }
    
    /// 监听键盘 frame 的变化
    @objc fileprivate func keyboardFrameChanged(notice: Notification) {
        /// 获取通知的信息
        let userInfo = notice.userInfo
        /// 获取键盘的 frame
        let keyboardFrame = userInfo?[UIKeyboardFrameEndUserInfoKey] as! CGRect
        /// 获取键盘叹气的时长
        let duration = userInfo?[UIKeyboardAnimationDurationUserInfoKey] as! Double
        /// 修改 toolbar 的底部约束
        composeWeiboToolBar.snp.updateConstraints { (make) in
            make.bottom.equalTo(self.view).offset(-(ScreenHeight - keyboardFrame.origin.y))
        }
        /// 动画
        UIView.animate(withDuration: duration) {
            self.view.layoutIfNeeded()
        }
    }
    
    /// 监听删除摁扭的事件
    @objc fileprivate func deleteTextAction(){
        /// 回删文本内容
        weiboContentTextView.deleteBackward()
    }
}
// MARK: toolBar摁扭的点击事件
@available(iOS 9.0, *)
extension LXJComposeWeiboController: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    /// 弹出表情键盘
    fileprivate func didEmoticonKeyBoard() -> Void {
        /// 表情键盘和系统键盘的切换
        if weiboContentTextView.inputView == nil {
            /// 系统键盘切换至表情键盘
            weiboContentTextView.inputView = emoticonKeyBoard
            /// 如果是表情键盘
            composeWeiboToolBar.switchEmoticonBackgroundImage(isEmoticon: true)
        } else{
            /// 表情键盘切换至系统键盘
            weiboContentTextView.inputView = nil
            /// 如果不是表情键盘
            composeWeiboToolBar.switchEmoticonBackgroundImage(isEmoticon: false)
        }
        /// 让键盘成为第一响应者
        weiboContentTextView.becomeFirstResponder()
        /// 重新加载输入视图
        weiboContentTextView.reloadInputViews()
    }
    
    /// 点击图片摁扭弹出图片选择器
    fileprivate func didSelectedPicture() -> Void {
        /// 创建图片选择器
        let imagePickerController = UIImagePickerController()
        /// 设置图片选择器的代理对象
        imagePickerController.delegate = self
        
        /// 判断照片来源
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            /// 相机可用 真机打开相机
            imagePickerController.sourceType = .camera
        }else{
            /// 图库可用 模拟器打开图库
            imagePickerController.sourceType = .photoLibrary
        }
        
        /// 判断前后摄像头是否可用'
        if UIImagePickerController.isCameraDeviceAvailable(.front) {
            /// 前置镜头可以使用
            print("前置摄像头可使用")
        }
        if UIImagePickerController.isCameraDeviceAvailable(.rear) {
            /// 后置镜头可以使用
            print("后置镜头可以使用")
        }
        
        /// modal 出图选择器
        self.present(imagePickerController, animated: true, completion: nil)
    }
    
    /// 实现UIImagePickerControllerDelegate的代理方法 不然无法 dismiss 掉图片选择器
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        /// 打印 info
        //        print(info)
        /// 获取图片
        var image = info[UIImagePickerControllerOriginalImage] as! UIImage
        /// 压缩图片
        image = compressImage(image: image)
        /// 添加到照片到多图视图
        composeWeiboPictures.addSelecetedImages(image: image)
        /// 得到图片后销毁图片选择器
        picker.dismiss(animated: true, completion: nil)
    }
    
    /// 压缩图片
    fileprivate func compressImage(image: UIImage) -> UIImage {
        /// 照片的宽度
        let imageWidth = ScreenWidth - CGFloat(2 * homeWeiboCellmargin)
        ///计算照片的高度
        let imageHeight = imageWidth / image.size.width * image.size.height
        /// 开启图片上下文
        UIGraphicsBeginImageContext(CGSize(width: imageWidth, height: imageHeight))
        /// 把图片压缩至指定区域内
        image.draw(in: CGRect(origin: CGPoint.zero, size: CGSize(width: imageWidth, height: imageHeight)))
        /// 通过上下文获取这张图片
        let scaleImage = UIGraphicsGetImageFromCurrentImageContext()
        /// 关闭图片上下文
        UIGraphicsEndImageContext()
        
        return scaleImage!
    }
}


//  MARK: ---UITextViewDelegate的代理方法
@available(iOS 9.0, *)
extension LXJComposeWeiboController: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        ///  根据文本框是否内容判断按钮是否可用
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
    }
    
    /// 拖拽的时候收起键盘
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        ///  键盘失去第一响应者
        self.view.endEditing(true)
    }
}
